package me.zhengjie.inter.service.impl;

import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.IdUtil;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import freemarker.ext.beans.HashAdapter;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import me.zhengjie.business.domain.AdlZhsq;
import me.zhengjie.business.domain.Gs;
import me.zhengjie.business.domain.Zhsq;
import me.zhengjie.business.domain.ZhsqHistory;
import me.zhengjie.business.repository.AdlZhsqRepository;
import me.zhengjie.business.repository.ZhsqHistoryRepository;
import me.zhengjie.business.repository.ZhsqPgRepository;
import me.zhengjie.business.repository.ZhsqRepository;
import me.zhengjie.business.service.dto.ZhsqDto;
import me.zhengjie.business.service.dto.ZhsqQueryCriteria;
import me.zhengjie.business.service.mapstruct.ZhsqMapper;
import me.zhengjie.domain.LocalStorage;
import me.zhengjie.inter.service.MpZhsqPgService;
import me.zhengjie.inter.service.MpZhsqService;
import me.zhengjie.repository.LocalStorageRepository;
import me.zhengjie.utils.*;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;

import javax.transaction.Transactional;
import java.math.BigDecimal;
import java.util.*;

/**
 * @description 服务接口
 * @author xiahongbo
 * @date 2022-07-10
 **/
@Slf4j
@Service
@RequiredArgsConstructor
public class MpZhsqPgServiceImpl implements MpZhsqPgService {

    private final AdlZhsqRepository adlZhsqRepository;
    private final LocalStorageRepository localStorageRepository;

    private final ZhsqPgRepository zhsqPgRepository;
    private final ZhsqRepository zhsqRepository;
    private final ZhsqHistoryRepository zhsqHistoryRepository;
    private final ZhsqMapper zhsqMapper;

    @Override
    public Page<Zhsq> queryAllByPgUserId(String zt, Long id, String zhlb, String blurry, Pageable pageable) {
        Page<Zhsq> page = zhsqPgRepository.queryAllByPgUserId(zt, id, zhlb, blurry, pageable);
        return page;
    }
    @Override
    @org.springframework.transaction.annotation.Transactional(rollbackFor = Exception.class)
    public void updateZhzt(String zt, Long id) {
        zhsqRepository.updateZhzt(zt, id);
        ZhsqHistory zhsqHistory = new ZhsqHistory();
        zhsqHistory.setId(IdUtil.simpleUUID());
        zhsqHistory.setUserId(SecurityUtils.getCurrentUserId());
        zhsqHistory.setZhsqId(id);
        zhsqHistory.setType("02");
        if(zt.equals("06")){
            zhsqHistory.setResult("通过");
        }else {
            zhsqHistory.setResult("未通过");
        }
        zhsqHistoryRepository.save(zhsqHistory);
    }

    @Override
    public Zhsq findById(Long id) {
        Optional<Zhsq> zhsq = zhsqPgRepository.findById(id);
        return zhsq.get();
    }


    @Override
    @Transactional
    public ZhsqDto updataPg(Zhsq resources, String ids) {
        log.info("移动端[MpZhsqServiceImpl - create]新增照护申请 {} ", resources);
        log.info("移动端[MpZhsqServiceImpl - create]新增照护图片 {} ", ids);
        // 获取已保存的评估ADL
        List<AdlZhsq>  adlZhsqs = adlZhsqRepository.findByBisAdlZhsqIdAndBisUserIdAndBisZfbsNull(resources.getBisZhsqId(),SecurityUtils.getCurrentUserId());
        // 计算并修改照护申请分数

        String[] adlIds = new String[adlZhsqs.size()];
        for (int i = 0; i < adlZhsqs.size(); i++) {
            AdlZhsq adl = adlZhsqs.get(i);
            adlIds[i] = adl.getAdlXmxxId();
        }
        log.info("移动端[MpZhsqServiceImpl - create]格式化自评主键 {} ", adlIds);
        String fs = adlZhsqRepository.queryScore(adlIds);
        log.info("移动端[MpZhsqServiceImpl - create]查询自评分数 {} ", fs);

        resources.setBisZhsqAdl(fs);
        // 修改申请状态
        resources.setBisZhsqZt(DefaultUtil.ZHZT_ZXZ);
        // 修改附件图片中的业务ID
        // 新增照片
        String[] picIds = ids.split(",");
        for (String picId:picIds) {
            Long storage_id = Long.parseLong(picId);
            LocalStorage localStorage = localStorageRepository.findById(storage_id).orElseGet(LocalStorage::new);
            localStorage.setYwid(String.valueOf(resources.getBisZhsqId()));
            localStorageRepository.save(localStorage);
        }
        return zhsqMapper.toDto(resources);
    }

    @Override
    public JSONObject findZhInfoAndAdlById(Long zhid) {

        List<Object> rsList = zhsqPgRepository.findZhInfoAndAdlById(zhid);

        JSONObject zhinfoObject = new JSONObject();
        JSONObject zhDetailObject = new JSONObject();

        Map<String, String> existAdlXmMap = new HashMap<>();

        JSONObject adlxmObject = null;
        JSONArray adlxxArray = null;
        for (Object obj : rsList) {
            Object[] arr = (Object[]) obj;


            String bis_zhsq_id = ((BigDecimal)arr[0]).toPlainString();
            String bis_zhsq_snry_xm = (String)arr[1];
            String bis_zhsq_snry_xb= (String)arr[2];
            String bis_zhsq_snry_sfz= (String)arr[3];
            String bis_zhsq_zt= (String)arr[4];
            String bis_zhsq_adl= (String)arr[5];
            String bis_zhsq_lxdh= (String)arr[6];
            String bis_zhsq_hldz= (String)arr[7];
            String bis_zhsq_jhrxm= (String)arr[8];
            String bis_zhsq_jhrdh= (String)arr[9];
            String bis_zhsq_gx= (String)arr[10];
            String bis_zhsq_sqyy= (String)arr[11];
            String bis_zhsq_adl_pc= (String)arr[12];
            String bis_adl_xm_id= (String)arr[13];
            String bis_adl_xm_name= (String)arr[14];
            String bis_adl_xm_px= ((BigDecimal)arr[15]).toPlainString();
            String bis_adl_xmxx_id= (String)arr[16];
            String bis_adl_xmxx_name= (String)arr[17];
            String bis_adl_xmxx_px= ((BigDecimal)arr[18]).toPlainString();
            String bis_adl_xmxx_fs= (String)arr[19];
            String is_default = (String)arr[20];

            if(!zhDetailObject.containsKey("zhdetail")) {
                zhDetailObject.put("bis_zhsq_id", bis_zhsq_id);
                zhDetailObject.put("bis_zhsq_snry_xm", bis_zhsq_snry_xm);
                zhDetailObject.put("bis_zhsq_snry_xb", bis_zhsq_snry_xb);
                zhDetailObject.put("bis_zhsq_snry_sfz", bis_zhsq_snry_sfz);
                zhDetailObject.put("bis_zhsq_zt", bis_zhsq_zt);
                zhDetailObject.put("bis_zhsq_adl", bis_zhsq_adl);
                zhDetailObject.put("bis_zhsq_lxdh", bis_zhsq_lxdh);
                zhDetailObject.put("bis_zhsq_hldz", bis_zhsq_hldz);
                zhDetailObject.put("bis_zhsq_jhrxm", bis_zhsq_jhrxm);
                zhDetailObject.put("bis_zhsq_jhrdh", bis_zhsq_jhrdh);
                zhDetailObject.put("bis_zhsq_gx", bis_zhsq_gx);
                zhDetailObject.put("bis_zhsq_sqyy", bis_zhsq_sqyy);
                zhDetailObject.put("bis_zhsq_adl_pc", bis_zhsq_adl_pc);

                zhinfoObject.put("zhdetail", zhDetailObject);
            }

            JSONObject adlxmxxObject = new JSONObject();
            adlxmxxObject.put("bis_adl_xmxx_id", bis_adl_xmxx_id);
            adlxmxxObject.put("bis_adl_xmxx_name", bis_adl_xmxx_name);
            adlxmxxObject.put("bis_adl_xmxx_px", bis_adl_xmxx_px);
            adlxmxxObject.put("bis_adl_xmxx_fs", bis_adl_xmxx_fs);
            adlxmxxObject.put("is_default", is_default);
            log.info("---- {} ", existAdlXmMap.containsKey(bis_adl_xm_id));
            if(!existAdlXmMap.containsKey(bis_adl_xm_id)) {

                existAdlXmMap.put(bis_adl_xm_id, bis_adl_xm_name);

                adlxmObject = new JSONObject();
                adlxmObject.put("bis_adl_xm_id", bis_adl_xm_id);
                adlxmObject.put("bis_adl_xm_name", bis_adl_xm_name);
                adlxmObject.put("bis_adl_xm_px", bis_adl_xm_px);

                adlxxArray = new JSONArray();
                log.info("111111----+ {} ", existAdlXmMap);
                log.info("111111----= {} ", adlxxArray);
            } else {
                adlxxArray.add(adlxmxxObject);
                adlxmObject.put("adlxxs", adlxxArray);
                zhinfoObject.put("adlxm", adlxmObject);
                log.info("222222----+ {} ", existAdlXmMap);
                log.info("222222----= {} ", adlxxArray);
            }
        }

        return zhinfoObject;
    }
}
